/*
 * @Author: xiawei 1243162387@qq.com
 * @Date: 2024-03-29 11:58:14
 * @LastEditors: xiawei 1243162387@qq.com
 * @LastEditTime: 2024-12-12 00:12:23
 */
import { createRouter, createWebHistory, type RouteRecordRaw } from 'vue-router';

import { dashboardRoutes } from './dashboard';
// import { settingRoutes } from './setting';
import { microAppRoutes } from './microApp';

import { getUserOfLocalStorage } from '@package/shared/utils';
import userStore from '@/stores/user';
import { registerApps } from '@/microApps'
import HistoryMemory from './historyMemory'

const historyMemory = new HistoryMemory({
    limit: 10
})
const baseRouter: Array<RouteRecordRaw> = [
    {
        path: '/login',
        name: 'Login',
        component: () => import('@/views/login/index.vue')
    }
];
const router = createRouter({
    history: createWebHistory(),
    routes: [
        ...dashboardRoutes,
        ...microAppRoutes,
        ...baseRouter,
    ]
});
// 白名单
const whiteRouters = ['/login'];
// 路由拦截
router.beforeEach(async (to: any, _from: any, next: any) => {
    history.replaceState({ ...history.state, current: _from.fullPath }, "", to.fullPath);
    let pullPath = historyMemory.push(to.fullPath)
    //白名单不需要验证用户是否登录
    if(whiteRouters.includes(to.path)){
        next()
    }else{
        const user = userStore();
        const LocalUser =  getUserOfLocalStorage();
        if(LocalUser.id){ // 已登录
            // 已登录检查是否store中是否保存了用户信息没有需要请求用户信息（列如：权限数据）
            if(!user.userInfo.id){
                try {
                    // 获取用户信息并且注入到store中
                    await user.addUser(LocalUser.id) 
                    // 动态注入子应用
                    registerApps()
                } catch (error) {
                    console.log(error)
                }
            }
            if(pullPath){
                next(pullPath) 
            }else{
                next() 
            }

        }else{
            // 未登录跳转到登录页面
            next('/login') 
        }
    }
})
export default router